import {Table,Icon,Row,Col,Button,Spin,Modal} from 'antd'
const confirm = Modal.confirm;
import {WeaTools,WeaInput,WeaSelect,WeaBrowser,WeaDatePicker,WeaCheckbox} from 'ecCom'
import './style/index.css'
import equal from "deep-equal"

class ContractPayTable extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			columns: props.columns || [],
			childColumns:props.childColumns ||[],
			datas: [],
			showGroup: props.showGroup ? props.showGroup : false,
			rowKeys:[]
		}
	}
	componentDidMount() {
		const { datas = [], columns = [] } = this.props;
		columns.length > 0 && this.setState(datas.length > 0 ? {datas: this.addKeytoDatas(datas),columns} : {columns})
	}
	componentWillReceiveProps(nextProps,nextState) {
		if(!equal(this.props.childColumns,nextProps.childColumns)){
			this.setState({childColumns: nextProps.childColumns})
		}
		if(!equal(this.props.columns,nextProps.columns)){
			this.setState({columns: nextProps.columns})
		}
	    if(!equal(this.props.datas,nextProps.datas)){
			this.setState({datas: this.addKeytoDatas(nextProps.datas)})
		}
	}
	shouldComponentUpdate(nextProps, nextState) {
		return !equal(this.props.datas, nextProps.datas) ||
			!equal(this.props.columns,nextProps.columns)||
			!equal(this.props.childColumns,nextProps.childColumns)||
			!equal(this.state.rowKeys,nextState.rowKeys)||
			!equal(this.state,nextState)||
			!equal(this.props.type,nextProps.type)
	}
	addKeytoDatas(datas){
		let rowKeys = [];
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			rowKeys.push(i);
			return _data
		})
		this.setState({rowKeys})
		return _datas
	}
	render() {
		const { datas,showGroup,columns ,rowKeys} = this.state;
		const {title,} = this.props;
		return(
			<div className="wea-crm-table-edit" >
				<Row className="wea-title">
                    <Col span="20">
                        <div>{title}</div>
                    </Col>
					<Col span="4" style={{textAlign:"right",paddingRight:10,fontSize:12}}>
						<Icon type={showGroup ? 'up' : 'down'} onClick={()=>this.setState({showGroup:!showGroup})}/>
	                </Col>
                </Row>
				<Row className="wea-content" style={{display:showGroup ? "block":"none"} }>
					<Col className="wea-form-cell" span={24}>
                        <Table 
							columns={this.getColumns(columns,"p")}
							dataSource={datas}
							pagination={false}
							//defaultExpandAllRows={true}
							expandedRowRender={(record)=>this.getExpendRowRender(record)}
							 onExpandedRowsChange={(expanded)=>{this.expendRowsChange(expanded)}}
							 expandedRowKeys={rowKeys}
						 	// onExpand={(expanded)=>{console.log(expanded)}}
                    	/>
					 </Col>
                </Row>
               
            </div>
		)
	}
	getColumns(columns,level){
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			_col.render = ( text, record, index ) => {
				return this.getColRender( _col, text, record, index,level );
			}
			return _col
		});
		return _columns
	}
	getColRender( _col, text, record, index ,level){
		const { com,} = _col;
		let _com = [];
		com.map(c => {
			if(typeof c.props === 'object' && level=="p"){
				_com.push(<Button type="primary" title='保存' size="small" style={{padding:"1px 3px"}} onClick={()=>this.saveRowList(record, index)}><Icon type="save" /></Button>);
			}else if(typeof c.props === 'object' ){
				_com.push(<span>
					<Button type="primary" title='保存' size="small" onClick={()=>this.saveDetailList(record, index,"save")}>保存</Button> &nbsp;&nbsp;
					<Button type="primary" title='删除' size="small" onClick={()=>this.saveDetailList(record, index,"delet")}>删除</Button>
			</span>);
			}else{
				const { domkey,viewAttr =2,  formItemType = 'INPUT', options = [], browserConditionParam = {}, width ,value ,type="text"} = c;
				const _type = formItemType.toUpperCase();
				_com.push(
					<span>
						{
							 _type === 'INPUT' && 
							<WeaInput 
								 defaultValue={value || ""} 
								value={record[domkey[0]]} 
								style={{width, display: 'inline-block'}}
								onBlur={value => this.onEdit(record, index, domkey[0], value)}
								viewAttr={viewAttr}
								type={type} /> 
						}
						{ _type === 'DATEPICKER' && 
							<WeaDatePicker
								value={record[domkey[0]]} 
								style={{width, display: 'inline-block'}}
								formatPattern={2}
								viewAttr={viewAttr}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
							/>
						}
						{ _type === 'CHECKBOX' &&  
							<WeaCheckbox
								value={record[domkey[0]]=="1"? true:false} 
								style={{width, display: 'inline-block'}}
								viewAttr={viewAttr}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
							/>
						}
						{ _type === 'BROWSER' && 
						<WeaBrowser 
							replaceDatas={this.getBrowerDatas(record, domkey[0])}
							{...browserConditionParam}
							style={{width, display: 'inline-block'}}
							//onChange={(ids, names, bDatas) => this.onEdit(record, index, domkey[0], ids, names, bDatas)}
						/> 
					}
					</span>
				)
			}
		});
		return (
			<div>
				{_com}
			</div>
		)
	}
	getBrowerDatas(record, key){
		let replaceDatas = [];
		if(record[key + 'span'] !== undefined) {
			let keys = record[key].split(',');
			let values = record[key + 'span'].split(',');
			if(keys.length === values.length){
				keys.map((k, i) => {
					replaceDatas.push({id: k, name: values[i]});
				});
			}else{
				console.log('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "');
			}
		}
		return replaceDatas
	}

	onEdit(record, index, key, value){
	//	console.log(record, index, key, value)
		record[key] = value
		const { datas, } = this.state;
		let _datas = [].concat(datas);
		_datas[index][key] = value;

		this.setState({datas: _datas});
		this.onChange(record, index, key, value);
	}

	
	getExpendRowRender=(record)=>{
		const {childColumns} = this.state;	
		return (
		  <Table
			columns={this.getColumns(childColumns)}
			dataSource={record.child.detail}
			pagination={false}
			footer={this.setFooter(record.child)}
			showHeader={false}
		  />
		);
	}
	setFooter(data){
		const {type } = this.props;
		return  <table><tbody ><tr>
			<td width='55%' style={{padding:"0 8px"}}> </td>
			<td width='10%' style={{padding:"0 8px",color:"red"}}>总计: </td>
			<td width='10%' style={{padding:"0 8px",color:"red"}}>{data.total}</td>
			<td width='10%' style={{padding:"0 8px",color:"red"}}>{type =="pay" ? <span>余额： {data.balance}</span>:""}</td>
			<td width='15%' style={{padding:"0 8px"}}></td>
			</tr></tbody></table>
	}
	
	onChange(record, index, key, value){
		typeof this.props.onChange === 'function' && this.props.onChange(record, index, key, value);
	}
	saveRowList=(record, index)=>{
		typeof this.props.payRowSave === 'function' && this.props.payRowSave(record, index);
	}
	saveDetailList=(record, index,type)=>{
		typeof this.props.payDetailHandle === 'function' && this.props.payDetailHandle(record, index,type);
	}
	expendRowsChange=(arr)=>{
		const {rowKeys} = this.state;
		const _rowKeys =  [].concat(rowKeys);
		let newArr = [];
		if(_rowKeys.indexOf(arr[0]) >= 0 ){
			newArr = (function(){
				let temp =[];
				for(let i=0;i< _rowKeys.length;i++){
					if(_rowKeys[i] == arr[0]){
						temp.push(_rowKeys[i])
					}
				}
				return temp
			})();
		}else{
			newArr =arr
		}
		this.setState({
			rowKeys:newArr
		})
	}
}

export default ContractPayTable;
